<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <!-- 使用CDN引入CSS -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/datatables.net-buttons-bs4/2.2.3/buttons.bootstrap4.min.css">
    <style>
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 15px 20px;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
        }
        .card-body {
            padding: 20px;
        }
        .status-active {
            color: #28a745;
            font-weight: bold;
        }
        .status-inactive {
            color: #dc3545;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <h2 class="mt-4 mb-4">用户管理</h2>
        
        <div class="card mb-4">
            <div class="card-header">
                <i class="fas fa-search mr-1"></i>查询条件
            </div>
            <div class="card-body">
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="username">用户名</label>
                            <input type="text" class="form-control" id="username" placeholder="输入用户名">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="nickName">昵称</label>
                            <input type="text" class="form-control" id="nickName" placeholder="输入昵称">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="status">状态</label>
                            <select id="status" class="form-control">
                                <option value="">全部</option>
                                <option value="0">正常</option>
                                <option value="1">停用</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <button type="button" class="btn btn-primary btn-block" id="searchBtn">
                                <i class="fas fa-search"></i> 查询
                            </button>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <button type="button" class="btn btn-secondary btn-block" id="resetBtn">
                                <i class="fas fa-redo"></i> 重置
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card mb-4">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-6">
                        <i class="fas fa-table mr-1"></i>用户列表
                    </div>
                    <div class="col-md-6 text-right">
                        <button type="button" class="btn btn-primary btn-sm" id="addBtn">
                            <i class="fas fa-plus"></i> 新增用户
                        </button>
                        <button type="button" class="btn btn-success btn-sm ml-2" id="exportBtn">
                            <i class="fas fa-file-excel"></i> 导出
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="userTable" class="table table-bordered" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>用户ID</th>
                                <th>用户名</th>
                                <th>昵称</th>
                                <th>邮箱</th>
                                <th>手机号</th>
                                <th>性别</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 表格数据将通过JavaScript动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 用户详情模态框 -->
    <div class="modal fade" id="userModal" tabindex="-1" role="dialog" aria-labelledby="userModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalLabel">用户详情</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="userDetails">
                        <!-- 用户详情将通过JavaScript动态生成 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 新增/编辑用户模态框 -->
    <div class="modal fade" id="addEditUserModal" tabindex="-1" role="dialog" aria-labelledby="addEditUserModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addEditUserModalLabel">新增用户</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="userForm">
                        <input type="hidden" id="userId" name="userId">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalUsername">用户名 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="modalUsername" name="modalUsername" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalNickName">昵称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="modalNickName" name="modalNickName" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalEmail">邮箱</label>
                                    <input type="email" class="form-control" id="modalEmail" name="modalEmail">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalPhone">手机号</label>
                                    <input type="text" class="form-control" id="modalPhone" name="modalPhone">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalSex">性别</label>
                                    <select class="form-control" id="modalSex" name="modalSex">
                                        <option value="0">男</option>
                                        <option value="1">女</option>
                                        <option value="2">未知</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalStatus">状态</label>
                                    <select class="form-control" id="modalStatus" name="modalStatus">
                                        <option value="0">正常</option>
                                        <option value="1">停用</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row" id="passwordRow">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalPassword">密码 <span class="text-danger">*</span></label>
                                    <input type="password" class="form-control" id="modalPassword" name="modalPassword">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="modalConfirmPassword">确认密码 <span class="text-danger">*</span></label>
                                    <input type="password" class="form-control" id="modalConfirmPassword" name="modalConfirmPassword">
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveUserBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 使用CDN引入JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/datatables.net-buttons/2.2.3/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/datatables.net-buttons/2.2.3/js/buttons.html5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // 初始化数据表格
            var table = $('#userTable').DataTable({
                language: {
                    "sProcessing": "处理中...",
                    "sLengthMenu": "显示 _MENU_ 项结果",
                    "sZeroRecords": "没有匹配结果",
                    "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                    "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                    "sInfoPostFix": "",
                    "sSearch": "搜索:",
                    "sUrl": "",
                    "sEmptyTable": "表中数据为空",
                    "sLoadingRecords": "载入中...",
                    "sInfoThousands": ",",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": "上页",
                        "sNext": "下页",
                        "sLast": "末页"
                    }
                },
                processing: true,
                serverSide: true,
                ajax: {
                    url: '/system/user/list',
                    type: 'POST',
                    contentType: 'application/json',
                    data: function(d) {
                        // 添加额外的请求参数
                        return JSON.stringify({
                            pageSize: d.length,
                            pageNum: (d.start / d.length) + 1,
                            username: $('#username').val(),
                            nickName: $('#nickName').val(),
                            status: $('#status').val()
                        });
                    },
                    dataSrc: function(json) {
                        // 处理返回的数据
                        if (json.code === 200 && json.data && json.data.rows) {
                            // 更新表格显示的总记录数
                            json.recordsTotal = json.data.total || json.data.rows.length;
                            json.recordsFiltered = json.data.total || json.data.rows.length;
                            
                            return json.data.rows.map(function(user) {
                                return [
                                    user.userId,
                                    user.username,
                                    user.nickName,
                                    user.email || '',
                                    user.phone || '',
                                    user.sex === '0' ? '男' : (user.sex === '1' ? '女' : '未知'),
                                    user.status === '0' ? '<span class="status-active">正常</span>' : '<span class="status-inactive">停用</span>',
                                    user.createTime || '',
                                    '<button class="btn btn-sm btn-info view-btn">查看</button> <button class="btn btn-sm btn-primary edit-btn">编辑</button> <button class="btn btn-sm btn-danger delete-btn">删除</button>'
                                ];
                            });
                        }
                        return [];
                    }
                },
                columns: [
                    { title: "用户ID" },
                    { title: "用户名" },
                    { title: "昵称" },
                    { title: "邮箱" },
                    { title: "手机号" },
                    { title: "性别" },
                    { title: "状态" },
                    { title: "创建时间" },
                    { title: "操作" }
                ]
            });
            
            // 查看用户详情
            $('#userTable').on('click', '.view-btn', function() {
                var data = table.row($(this).parents('tr')).data();
                
                // 构建用户详情HTML
                var detailsHtml = `
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>用户ID：</strong> ${data[0]}
                        </div>
                        <div class="col-md-6">
                            <strong>用户名：</strong> ${data[1]}
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>昵称：</strong> ${data[2]}
                        </div>
                        <div class="col-md-6">
                            <strong>邮箱：</strong> ${data[3]}
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>手机号：</strong> ${data[4]}
                        </div>
                        <div class="col-md-6">
                            <strong>性别：</strong> ${data[5]}
                        </div>
                    </div>
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <strong>状态：</strong> ${data[6]}
                        </div>
                        <div class="col-md-6">
                            <strong>创建时间：</strong> ${data[7]}
                        </div>
                    </div>
                `;
                
                $('#userDetails').html(detailsHtml);
                $('#userModal').modal('show');
            });
            
            // 编辑用户
            $('#userTable').on('click', '.edit-btn', function() {
                var data = table.row($(this).parents('tr')).data();
                
                // 填充表单
                $('#userId').val(data[0]);
                $('#modalUsername').val(data[1]);
                $('#modalNickName').val(data[2]);
                $('#modalEmail').val(data[3]);
                $('#modalPhone').val(data[4]);
                $('#modalSex').val(data[5] === '男' ? '0' : (data[5] === '女' ? '1' : '2'));
                $('#modalStatus').val(data[6].includes('正常') ? '0' : '1');
                
                // 隐藏密码字段
                $('#passwordRow').hide();
                
                $('#addEditUserModalLabel').text('编辑用户');
                $('#addEditUserModal').modal('show');
            });
            
            // 删除用户
            $('#userTable').on('click', '.delete-btn', function() {
                var data = table.row($(this).parents('tr')).data();
                if (confirm('确定要删除用户 "' + data[1] + '" 吗？')) {
                    $.ajax({
                        url: '/system/user/delete',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({userId: data[0]}),
                        success: function(res) {
                            if (res.code === 200) {
                                alert('删除成功');
                                table.ajax.reload();
                            } else {
                                alert('删除失败: ' + res.msg);
                            }
                        },
                        error: function() {
                            alert('服务器错误，请稍后再试');
                        }
                    });
                }
            });
            
            // 新增用户按钮点击事件
            $('#addBtn').click(function() {
                // 重置表单
                $('#userForm')[0].reset();
                $('#userId').val('');
                
                // 显示密码字段
                $('#passwordRow').show();
                
                $('#addEditUserModalLabel').text('新增用户');
                $('#addEditUserModal').modal('show');
            });
            
            // 保存用户按钮点击事件
            $('#saveUserBtn').click(function() {
                // 表单验证
                if (!$('#userForm')[0].checkValidity()) {
                    $('#userForm')[0].reportValidity();
                    return;
                }
                
                // 收集表单数据
                var formData = {
                    userId: $('#userId').val(),
                    username: $('#modalUsername').val(),
                    nickName: $('#modalNickName').val(),
                    email: $('#modalEmail').val(),
                    phone: $('#modalPhone').val(),
                    sex: $('#modalSex').val(),
                    status: $('#modalStatus').val()
                };
                
                // 如果是新增，添加密码
                var userId = $('#userId').val();
                if (!userId) {
                    if ($('#modalPassword').val() !== $('#modalConfirmPassword').val()) {
                        alert('两次输入的密码不一致');
                        return;
                    }
                    formData.password = $('#modalPassword').val();
                }
                
                // 发送请求到后端保存用户
                $.ajax({
                    url: '/system/user/' + (userId ? 'update' : 'add'),
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(res) {
                        if (res.code === 200) {
                            alert('操作成功');
                            $('#addEditUserModal').modal('hide');
                            table.ajax.reload();
                        } else {
                            alert('操作失败: ' + res.msg);
                        }
                    },
                    error: function() {
                        alert('服务器错误，请稍后再试');
                    }
                });
            });
            
            // 查询按钮点击事件
            $('#searchBtn').click(function() {
                table.ajax.reload();
            });
            
            // 重置按钮点击事件
            $('#resetBtn').click(function() {
                $('#username').val('');
                $('#nickName').val('');
                $('#status').val('');
                table.ajax.reload();
            });
            
            // 导出按钮点击事件
            $('#exportBtn').click(function() {
                var queryParams = {
                    username: $('#username').val(),
                    nickName: $('#nickName').val(),
                    status: $('#status').val()
                };
                
                // 构建查询参数
                var params = $.param(queryParams);
                window.location.href = '/system/user/export?' + params;
            });
        });
    </script>
</body>
</html> 